﻿using System;
using System.Collections.Generic;
using System.Linq;
using log4net;
using StockFinder.Model;
using StockFinder.YahooFinance;

namespace StockFinder.StockLists.SymbolListEnumerators
{
    public abstract class YahooFinanceOfflinePriceLoaderSymbolListEnumerator : IStockList
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(YahooFinanceOfflinePriceLoaderSymbolListEnumerator)); 
        private int _Index = -1;
        private Dictionary<Symbol, string> _Symbols;
        private readonly YahooFinanceCsvStockPriceHistoryExtractor _YahooFinanceCsvStockPriceHistoryExtractor = new YahooFinanceCsvStockPriceHistoryExtractor();
        private Symbol _Previous;

        protected abstract Dictionary<Symbol, string> GetSymbols();

        private Dictionary<Symbol, string> Symbols
        {
            get { return _Symbols ?? (_Symbols = GetSymbols()); }
        }

        private Symbol GetCurrentSymbol()
        {
            var symbol = _Symbols.ElementAt(_Index);

            try
            {
                symbol.Key.Prices = _YahooFinanceCsvStockPriceHistoryExtractor.GetHistoricPrices(symbol.Value);
            }
            catch (Exception exception)
            {
                Log.ErrorFormat(exception.ToString());
            }

            return symbol.Key;
        }

        public Symbol Current
        {
            get
            {
                /* we need to keep a record of the last symbol retrieved so we can clear prices
                 * otherwise we will get lots of symbols in memory with lots of prices which arent required                 
                 */

                if (_Previous != null && _Previous.Prices != null)
                {
                    _Previous.Prices.Clear();
                    _Previous.Prices = null;
                }

                _Previous = GetCurrentSymbol();

                return _Previous;
            }
        }

        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public bool MoveNext()
        {
            _Index++;
            return _Index < Symbols.Count;
        }

        public void Reset()
        {
            _Index = -1;
        }

        object System.Collections.IEnumerator.Current
        {
            get { return Current; }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public IEnumerator<Symbol> GetEnumerator()
        {
            return this;
        }

        public int Count
        {
            get
            {
                return Symbols != null ? Symbols.Count : 0;
            }
        }

        public string Name { get; set; }
    }
}
